#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>

int main(int argc,char *argv[])
{
	if(argc!=3){
		printf("Usage: %s [server:ip] [server.port]",argv[0]);
		return 1;
	}
	
	int listen_sock=socket(AF_INET,SOCK_STREAM,0);
	if(listen_sock<0){
		perror("socket");
		return 2;
	}
	
	struct sockaddr_in local;
	local.sin_family=AF_INET;
	local.sin_port=htons(atoi(argv[2]));
	local.sin_addr.s_addr=inet_addr(argv[1]);

	if(bind(listen_sock,(struct sockaddr*)&local,sizeof(local))<0){
		perror("bind");
		return 3;
	}

	if(listen(listen_sock,5)<0){
		perror("listen");
		return 4;
	}

	for( ; ;){
		struct sockaddr_in client;
		socklen_t len=sizeof(client);
		int sock=accept(listen_sock,(struct sockaddr*)&client,&len);
		if(sock<0){
			perror("accept");
			continue;
		}
		
		char request[10240]={0};
		size_t s=read(sock,request,sizeof(request)-1);
		if(s>0){
			request[s]=0;
			printf("[Request] %s",request);
			const char * hello="<h1>hello world</h1>";
			sprintf(resquest,"HTTP/1.0 200 OK\nContent-Length:%lu\n\n%s",strlen(hello),hello);
			write(sock,response,strlen(response));
		}
	}
}

























